package com.wbb.realm;

import com.wbb.api.AdminAPI;
import com.wbb.api.SellerAPI;
import com.wbb.bean.LoginUsernamePasswordToken;
import com.wbb.constant.LoginConstants;
import com.wbb.model.TbAdmin;
import com.wbb.model.TbSeller;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

public class LoginRealm extends AuthorizingRealm {
    @Autowired
    private AdminAPI adminAPI;

    @Autowired
    private SellerAPI sellerAPI;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取参数
        LoginUsernamePasswordToken usernamePasswordToken = (LoginUsernamePasswordToken) authenticationToken;
        // 获取账号
        String username = usernamePasswordToken.getUsername();
        String type = usernamePasswordToken.getType();
        if (Objects.equals(type, LoginConstants.ADMIN)){
            // 从数据库中获取数据
            TbAdmin admin = adminAPI.queryByUsername(username);
            if (admin == null) return null;
            // 校验密码
            SimpleAuthenticationInfo loginRealm = new SimpleAuthenticationInfo(admin,admin.getPassword(), ByteSource.Util.bytes(admin.getSalt()),"adminRealm");
            System.out.println("认证操作");
            return loginRealm;
        }else {
            TbSeller seller = sellerAPI.queryByUsername(username);
            if (seller == null) return null;
            // 校验密码
            SimpleAuthenticationInfo loginRealm = new SimpleAuthenticationInfo(seller,seller.getPassword(), ByteSource.Util.bytes(seller.getSalt()),"sellerRealm");
            System.out.println("认证操作");
            return loginRealm;
        }
    }
}
